package com.example.forum.controller;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.config.AppConfig;
import com.example.forum.model.User;
import com.example.forum.services.IUserService;
import com.example.forum.utils.MD5Util;
import com.example.forum.utils.StringUtil;
import com.example.forum.utils.UUIDUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

@Slf4j
//返回数据的Controller
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    public IUserService userService;
    @PostMapping("/register")
    public AppResult register(String username, String nickname, String password, String passwordRepeat){
        if (StringUtil.isEmpty(username) || StringUtil.isEmpty(nickname)
        || StringUtil.isEmpty(password) || StringUtil.isEmpty(passwordRepeat)){
            //返回错误信息
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        //校验密码与重复密码是否相同
        if (!password.equals(passwordRepeat)){
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            //返回错误信息
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);

        // 加密密码
       
        String salt = UUIDUtil.UUID_32();


        String encryptPassword = MD5Util.md5Salt(password,salt);
                //MD5Utils.md5Salt(password, salt);//32
        // 设置密码

        user.setPassword(encryptPassword);
        user.setSalt(salt);
        // 调⽤Service
        userService.createNormalUser(user);
        //  返回

        return AppResult.success();

    }

    //用户登录
    @PostMapping("/login")
    public AppResult login(HttpServletRequest request,
                           @NonNull String username,@NonNull String password){
        //调用Service中的登录方法 返回User对象
        User user = userService.login(username,password);

        //把User对象设置到Session作用域中
        HttpSession session = request.getSession(true);
        session.setAttribute(AppConfig.USER_SESSION,user);
        //返回结果
        return AppResult.success();
    }

    //获取用户信息
    @GetMapping("/info")
    public AppResult<User> getUserInfo (HttpServletRequest request,
                                        @RequestParam(value = "id",required = false) Long id){
        User user = null;
        if (id == null){
            HttpSession session = request.getSession(false);
//            if (session == null || session.getAttribute(AppConfig.USER_SESSION) == null){
//                //用户未登录，返回错误信息
//                return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
//            }
            user = (User) session.getAttribute(AppConfig.USER_SESSION);
        }else {
            //按id查询用户信息
            user = userService.selectById(id);
        }
        if (user == null){
            return AppResult.failed(ResultCode.FAILED_NOT_EXISTS);
        }
        return AppResult.success(user);
    }

    @GetMapping("/logout")
    public AppResult logout (HttpServletRequest request){
        //获取Session对象
        HttpSession session = request.getSession(false);
        //判断Session是否有效
        if (session != null){
            log.info("退出成功");
            session.invalidate();//直接销毁Session
        }
        return AppResult.success("退出成功");
    }

    //修改个人信息
    @PostMapping("/modifyInfo")
    public AppResult modifyInfo (HttpServletRequest request,
                                 @RequestParam(value = "username",required = false) String username,
                                 @RequestParam(value = "nickname",required = false) String nickname,
                                 @RequestParam(value = "gender",required = false) Byte gender,
                                 @RequestParam(value ="email",required = false) String email,
                                 @RequestParam(value = "phoneNum",required = false) String phoneNum,
                                 @RequestParam(value = "remark",required = false) String remark) {
        //非空校验
        if (StringUtil.isEmpty(username) && StringUtil.isEmpty(nickname) && StringUtil.isEmpty(email)
        && StringUtil.isEmpty(phoneNum) && StringUtil.isEmpty(remark) && gender == null){
            return AppResult.failed("请输入要修改的内容");
        }
        //从Session中获取用户Id
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        User updateUser = new User();

        updateUser.setId(user.getId());
        updateUser.setUsername(username);
        updateUser.setNickname(nickname); // 昵称
        updateUser.setGender(gender); // 性别
        updateUser.setEmail(email); // 邮箱
        updateUser.setPhoneNum(phoneNum); // 电话
        updateUser.setRemark(remark); // 个⼈简介
        //调⽤Service
        userService.modifyInfo(updateUser);
        //查询最新的用户信息
        user = userService.selectById(user.getId());
        //把最新的⽤⼾信息设置到session中
        session.setAttribute(AppConfig.USER_SESSION, user);
        //返回结果
        return AppResult.success(user);

    }

    //修改密码
    @PostMapping("/modifyPwd")
    public AppResult modifyPassword (HttpServletRequest request,
                                     @RequestParam("oldPassword") @NonNull String oldPassword,
                                     @RequestParam("newPassword") @NonNull String newPassword,
                                     @RequestParam("passwordRepeat") @NonNull String passwordRepeat) {
        //校验新密码与确认密码是否相同
        if (!newPassword.equals(passwordRepeat))
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        //获取当前用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //调用Service
        userService.modifyPassword(user.getId(), newPassword,oldPassword);
        return AppResult.success();
    }
    }


























